//
//  BaseTabBarController.m
//  coldjoke-ios-client
//
//  Created by ColdWorks on 12-8-26.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "BaseTabBarController.h"
#import "BaseBadgeView.h"
#import "UserManager.h"
#import "RegisterViewController.h"
#import "LoginViewController.h"
#import "JudgeViewController.h"

@implementation BaseTabBarController

@synthesize backGroundImageView;
@synthesize slideBg;
@synthesize tabItems = _tabItems;
@synthesize focusImages = _focusImages;
@synthesize darkImages = _darkImages;
@synthesize currentIndex;
@synthesize lastIndex;

- (id) init
{
    self = [super init];
    if (self) {
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self prepare];
    [self hideRealTabBar];
    [self initCustomTabBar];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void) dealloc{
    PP_RELEASE(backGroundImageView);
    PP_RELEASE(slideBg);
    PP_RELEASE(_tabItems);
    PP_RELEASE(_focusImages);
    PP_RELEASE(_darkImages);
	[super dealloc];
}

- (void) prepare
{
    backGroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 49)];
    backGroundImageView.image = [UIImage imageNamed:@"nav_bg.png"];
    slideBg = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"nav_bg_focus.png"]];
    currentIndex = 0;
    lastIndex = -1;
    
    //布置tabBar导航图片
    NSMutableArray *tFocusImages = [[NSMutableArray alloc] initWithObjects:
                                    [UIImage imageNamed:@"nav_home_focus.png"], 
                                    [UIImage imageNamed:@"nav_topic_focus.png"], 
                                    [UIImage imageNamed:@"nav_judge_focus.png"],
                                    [UIImage imageNamed:@"nav_more_focus.png"], nil];
    self.focusImages = tFocusImages;
    [tFocusImages release];
    
    NSMutableArray *tDarkImages = [[NSMutableArray alloc] initWithObjects:
                                   [UIImage imageNamed:@"nav_home_dark.png"], 
                                   [UIImage imageNamed:@"nav_topic_dark.png"], 
                                   [UIImage imageNamed:@"nav_judge_dark.png"], 
                                   [UIImage imageNamed:@"nav_more_dark.png"], nil];
    self.darkImages = tDarkImages;
    [tDarkImages release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"hideTabBar" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(hideTabBar)
                                                 name: @"hideTabBar"
                                               object: nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"showTabBar" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(showTabBar)
                                                 name: @"showTabBar"
                                               object: nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"setBadge" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(setBadge:)
                                                 name: @"setBadge"
                                               object: nil];
}

//static BOOL FIRSTTIME =YES;
//
//- (void)viewDidAppear:(BOOL)animated{
//	if (FIRSTTIME) {
//        [self prepare];
//		[self hideRealTabBar];
//		[self initCustomTabBar];
//		FIRSTTIME = NO;
//	}
//}

//设置badge
- (void)setBadge:(NSNotification *)_notification{
	NSString *badgeValue = [_notification object];
	UIButton *btn = [_tabItems objectAtIndex:self.selectedIndex];
	BaseBadgeView *badgeView = [[BaseBadgeView alloc] initWithFrame:CGRectMake(btn.bounds.size.width/2, 0, 30, 20)];
	badgeView.badgeString = badgeValue;
	badgeView.badgeColor = [UIColor blueColor];
	badgeView.tag = self.selectedIndex;
	badgeView.delegate = self;
	[btn addSubview:badgeView];
	[badgeView release];
}

- (void)hideRealTabBar{
	for(UIView *view in self.view.subviews){
		if([view isKindOfClass:[UITabBar class]]){
			view.hidden = YES;
			break;
		}
	}
}

//自定义tabbar
- (void)initCustomTabBar{
	//获取tabbar的frame
	CGRect tabBarFrame = self.tabBar.frame;
	myTabBarView = [[UIView alloc] initWithFrame:tabBarFrame];
    
	//设置tabbar背景
	[myTabBarView addSubview:backGroundImageView];
	[backGroundImageView release];
	myTabBarView.backgroundColor = [UIColor blackColor];
	[myTabBarView addSubview:slideBg];
	
	//创建按钮
	int viewCount = self.viewControllers.count < 5 ? 5 : self.viewControllers.count;
	self.tabItems = [NSMutableArray arrayWithCapacity:viewCount];
	double _width = 320 / viewCount;
	double _height = self.tabBar.frame.size.height;
	for (int i = 0; i < viewCount; i++) {
		UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
		btn.frame = CGRectMake(i*_width, 0, _width, _height);
		[btn addTarget:self action:@selector(selectedTab:) forControlEvents:UIControlEventTouchDown];
		btn.tag = i;
        //定义图片
        UIImage *t = i>0 ? (UIImage *)[self.darkImages objectAtIndex:i] : (UIImage *)[self.focusImages objectAtIndex:i];
		[btn setImage:t forState:UIControlStateNormal];
		[btn setImageEdgeInsets:UIEdgeInsetsMake(-10, 0, 0, 0)];
		//添加标题
		UIViewController *v = [self.viewControllers objectAtIndex:i];
		UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, _height-18, _width, _height-30)];
		titleLabel.backgroundColor = [UIColor clearColor];
		titleLabel.text = v.tabBarItem.title;
		[titleLabel setFont:[UIFont systemFontOfSize:12]];
		titleLabel.textAlignment = 1;
		titleLabel.textColor = [UIColor whiteColor];
		[btn addSubview:titleLabel];
		[titleLabel release];		
		
		[self.tabItems addObject:btn];
        
		//添加按钮之间的分割线,第一个位置和最后一个位置不需要添加
        //		if (i>0 && i<4) {
        //			UIImageView *splitView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"split"]];
        //			splitView.frame = CGRectMake(i*_width-1,0,splitView.frame.size.width,splitView.frame.size.height);
        //			[myTabBarView addSubview:splitView];
        //			[splitView release];
        //		}
		
		//添加Badge
		if (v.tabBarItem.badgeValue) {
			BaseBadgeView *badgeView = [[BaseBadgeView alloc] initWithFrame:CGRectMake(_width/2, 0, 30, 20)];
			badgeView.badgeString = v.tabBarItem.badgeValue;
			badgeView.badgeColor = [UIColor orangeColor];
			[btn addSubview:badgeView];
			[badgeView release];
		}
		[myTabBarView addSubview:btn];
	}
	[self.view addSubview:myTabBarView];
	[myTabBarView release];
	[self performSelector:@selector(slideTabBg:) withObject:[self.tabItems objectAtIndex:currentIndex]];
}

//切换tabbar
- (void)selectedTab:(UIButton *)button
{
	if (currentIndex == button.tag) {
		[[self.viewControllers objectAtIndex:button.tag] popToRootViewControllerAnimated:YES];
		return;
	}
    
    lastIndex = currentIndex;
	currentIndex = button.tag;
	self.selectedIndex = currentIndex;
    
    if (lastIndex >= 0) {
        //将上次的选中效果取消
        UIButton *lastItem = (UIButton *)[self.tabItems objectAtIndex:lastIndex];
        UIImage *t = (UIImage *)[self.darkImages objectAtIndex:lastIndex];
		[lastItem setImage:t forState:UIControlStateNormal];
    }
    if (currentIndex >= 0) {
        //高亮本次选中效果
        UIImage *t = (UIImage *)[self.focusImages objectAtIndex:currentIndex];
		[button setImage:t forState:UIControlStateNormal];
    }
    
	[self performSelector:@selector(slideTabBg:) withObject:button];
}

//切换滑块位置
- (void)slideTabBg:(UIButton *)btn{
	[UIView beginAnimations:nil context:nil];  
	[UIView setAnimationDuration:0.20];  
	[UIView setAnimationDelegate:self];
	slideBg.frame = btn.frame;
	[UIView commitAnimations];
	CAKeyframeAnimation * animation; 
	animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; 
	animation.duration = 0.50;
	animation.delegate = self;
	animation.removedOnCompletion = YES;
	animation.fillMode = kCAFillModeForwards;
	NSMutableArray *values = [NSMutableArray array];
	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]]; 
	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]]; 
	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
	animation.values = values;
	[btn.layer addAnimation:animation forKey:nil];
}

//切换tabbar
- (void)select:(int)index{
    Log(@"index :%d",index);
    UIButton *button = (UIButton *)[self.tabItems objectAtIndex:index];
    [self selectedTab:button];
}

//动画结束回调
- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    if (anim.duration==0.1) {
    }else if(anim.duration==0.25){
    }
}

//自定义tabbar
- (void)showTabBar{
    Log(@"mark");
    if(myTabBarView.hidden==NO){
        return;
    }
    [self performSelector:@selector(hideRealTabBar)];
    [myTabBarView setHidden:NO];
//    CAKeyframeAnimation * animation;
//	animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"]; 
//	animation.duration = 0.25;
//	animation.delegate = self;
//	animation.removedOnCompletion = YES;
//	animation.fillMode = kCAFillModeForwards;
//	NSMutableArray *values = [NSMutableArray array];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.0, 0.0, 0.0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
//    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
//	animation.values = values;
//	[myTabBarView.layer addAnimation:animation forKey:nil];
    UIView *contentView;
    if ([[self.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]]){
        contentView = [self.view.subviews objectAtIndex:1];
    } else {
        contentView = [self.view.subviews objectAtIndex:0];
    }
    contentView.frame = CGRectMake(contentView.bounds.origin.x, contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height - self.tabBar.frame.size.height);
}

//隐藏tabbar
- (void)hideTabBar{
    Log(@"mark");
    if(myTabBarView.hidden==YES){
        return;
    }
    [self performSelector:@selector(hideRealTabBar)];
    //    CAKeyframeAnimation * animation;
    //	animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    //	animation.duration = 0.1;
    //	animation.delegate = self;
    //	animation.removedOnCompletion = YES;
    //	animation.fillMode = kCAFillModeForwards;
    //	NSMutableArray *values = [NSMutableArray array];
    //	[values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    //    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.5, 0.5, 1.0)]];
    //    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.0, 0.0, 0.0)]];
    //	animation.values = values;
    //	[myTabBarView.layer addAnimation:animation forKey:nil];
    UIView *contentView;
    if ( [[self.view.subviews objectAtIndex:0] isKindOfClass:[UITabBar class]] ){
        contentView = [self.view.subviews objectAtIndex:1];
    }else{
        contentView = [self.view.subviews objectAtIndex:0];
    }
    contentView.frame = CGRectMake(contentView.bounds.origin.x,  contentView.bounds.origin.y,  contentView.bounds.size.width, contentView.bounds.size.height + self.tabBar.frame.size.height);
    [myTabBarView setHidden:YES];
}

@end

